<?php
# http://projects:8081/cdapp-2kt-api/api/request_sipds.php

header('Content-type: application/json');

include_once '_portal.php';
include_once '_envs.php';
include_once 'request_sipds_soap_lib.php';

// terminate request SIPDS
if (get_variable('STOP_ALL_NETWORK') === 1) {
  die('Network Stoped');
}
if (get_variable('STOP_SIPDS') === 1) {
  die('SIPDS Stoped');
}

function request_sipds($payload, $name_only = true) {
  $api = $name_only ? SIPDS_API[$payload] : $payload;
  $log = SIPDS_ENABLE_LOG && !SIPDS_FAKE_RESPONSE;
  $response = '';
  if (SIPDS_FAKE_RESPONSE) {
    $response = $api['fake'];
  } else {
    $response = post_xml($api['url'], $api['xml']);
  }
  if ($log) {
    logfile('REQUEST_SIPDS_URL', $api['url']);
    logfile('REQUEST_SIPDS_TX', $api['xml']);
    logfile('REQUEST_SIPDS_RX', $response);
  }
  if ($response == '') {
    $log ? logfile('REQUEST_SIPDS_EX', '!!! NULL RESPONSE !!!') : null;
    return ['status' => 0, 'data' => []];
  } else {
    $output = parse_xml($response);
    $log ? logfile('REQUEST_SIPDS_EX', json_stringify($output)) : null;
    return ['status' => 1, 'data' => $output];
  }
}

function post_xml($api_path, $xml_data) {
  if (!extension_loaded("curl")) {
    trigger_error("php curl model required!", E_USER_ERROR);
  }
  try {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $api_path);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 5);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type:text/xml; charset=utf-8"));
    curl_setopt($curl, CURLOPT_POSTFIELDS, $xml_data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $return_xml = curl_exec($curl);
    // logfile('XML_RESPONSE', $return_xml);
    curl_close($curl);
  } catch (Exception $e) {
    logfile('XML_RESPONSE', $e->getMessage());
  }
  return $return_xml;
}

function parse_xml($xml_data) {
  if (!$xml_data) {
    return [];
  }
  $parser = xml_parser_create_ns();
  xml_parse_into_struct($parser, $xml_data, $value_arr, $index_arr);
  xml_parser_free($parser);
  // var_dump($value_arr);
  return parse_xml_object(parse_xml_key_value_array($value_arr, 6, 0));
}

function parse_xml_key_value_array($value_arr_raw, $target_level = 6, $start_key = 0) {
  $value_arr = json_decode(json_encode($value_arr_raw), true);
  $output = [];
  $got_brother = false;
  $got_children = false;
  foreach ($value_arr as $key => $value) {
    if ($start_key > $key) {
      continue;
    } elseif ($value['type'] == 'close') {
      continue;
    }
    if ($value['level'] == $target_level) {
      $got_brother = true;
      $got_children = false;
      array_push($output, ['key' => $value['tag'], 'value' => isset($value['value']) ? $value['value'] : null]);
      continue;
    }
    if ($value['level'] == $target_level + 1 && !$got_children) {
      $got_children = true;
      $children = parse_xml_key_value_array($value_arr, $target_level + 1, $key);
      $output[count($output) - 1]['value'] = $children;
      continue;
    }
    if ($value['level'] < $target_level && $got_brother) {
      break;
    }
  }
  return $output;
}

function parse_xml_object($data_arr) {
  $output = [];
  $key_duplicate = false;
  $keys = [];
  foreach ($data_arr as $value) {
    if (in_array($value['key'], $keys, true)) {
      $key_duplicate = true;
      break;
    } else {
      array_push($keys, $value['key']);
    }
  }
  foreach ($data_arr as $value) {
    if (is_array($value['value'])) {
      if ($key_duplicate) {
        array_push($output, parse_xml_object($value['value']));
      } else {
        $output[$value['key']] = parse_xml_object($value['value']);
      }
    } else {
      $val = $value['value'];
      if (is_numeric($val) && substr($val, 0, 1) != '0') {
        $val = $val + 0;
      } elseif ($val == 'true') {
        $val = true;
      } elseif ($val == 'false') {
        $val = false;
      }
      if ($key_duplicate) {
        array_push($output, $val);
      } else {
        $output[$value['key']] = $val;
      }
    }
  }
  return $output;
}
